<?php
declare(strict_types=1);
namespace app\index\controller;
use aphp\core\Jump;
use aphp\core\Tool;

class Book
{
    use Jump;
    protected array $middleware = [
        'auth' => ['except' => ['index','detail','last','down']], // 除外
    ];

    public function index()
    {
        return view();
    }

    public function vip()
    {
        return view();
    }

    // 文集详情
    public function detail(int $id)
    {
        $vo = db('book')->where('id', $id)->where('status=1')->find();
        if (!$vo) {
            $this->error('文集不存在');
        }
        // 获取成员数
        $member_count = db('book_member')->where('book_id', $id)->where('status=1')->count();
        // 权限等级判断
        // $prem_type = 0 申请阅读 申请编辑
        // $prem_type = 1 阅读
        // $prem_type = 2 阅读 申请编辑
        $prem_level = get_prem_level($vo['id']); //0 无权限 1. 成员 2 编辑 3 创建者或超管
        $prem_type = 0;
        if ($vo['is_public'] == 1) {
            $prem_type = $prem_level < 2 ? 2 : 1;
        } elseif ($prem_level == 1) {
            $prem_type = 2;
        } elseif ($prem_level >= 2) {
            $prem_type = 1;
        }
        return view()->with(['vo' => $vo, 'prem_type' => $prem_type, 'member_count' => $member_count]);
    }

    // 申请成员
    public function join(int $id, int $level = 1)
    {
        if ($this->isAjax()) {
            $user = session('user');
            if (!$user) {
                $this->error('请先登录');
            }
            $join_level = ($level >= 2) ? 2 : 1; // 申请级别 1 viewer 2 editor
            $find = db('book_member')->where('book_id', $id)->where('user_id', $user['id'])->find();
            if ($find) {
                if ($find['status'] == 0 || $find['is_upgrade'] == 1) {
                    $this->error('已存在申请，请等待审核...');
                }
                if ($find['status'] == 1 && $join_level > $find['role_level'] && $find['is_upgrade'] == 0) {
                    $r = db('book_member')->where('id', $find['id'])->setField('is_upgrade', 1);
                    if ($r) {
                        cache_clear();
                        cli('clear:runtime index common');
                    }
                    $this->_jump(['已提交申请，请等待审核...', '申请失败'], $r, 'book/detail?id=' . $id);
                }
                $this->error('已是成员，请不要重复申请。');
            }
            $data = [
                'book_id' => $id,
                'user_id' => $user['id'],
                'role_level' => $join_level,
                'create_time' => time(),
            ];
            $r = db('book_member')->insert($data);
            if ($r) {
                cache_clear();
                cli('clear:runtime index common');
            }
            $this->_jump(['已提交申请，请等待审核...', '申请失败'], $r, 'book/detail?id=' . $id);
        }
        $this->error('非法操作');
    }

    public function down(int $id)
    {
        // 初始化目录
        $book = db('book')->field('id,sign,title,is_public')->where('id', $id)->where('status=1')->find();
        if (!$book) {
            $this->error('文集不存在');
        }
        // 检测权限
        if ($book['is_public'] != 1 && !check_prem_level(1, $book['id'])) {
            $this->error('没有权限进行此操作');
        }
        $book_name = $book['sign'];
        $dir = ROOT_PATH . '/public/down/' . $book_name; // 文档目录
        if (is_dir($dir)) {
            Tool::dir_delete($dir);
        } else {
            Tool::dir_init($dir, 0777);
        }
        // 生成文档文件到目录
        $list = db('doc')->field('id,book_id,sign,markdown,update_time')->where('book_id', $id)->where('status=1')->order('sort ASC,id ASC')->select();
        foreach ($list as $vo) {
            $foot = "\n\n---\n\n本文档由 [AphpDoc](https://doc.aphp.top) 生成，更新于：" . date('Y-m-d H:i:s', $vo['update_time']);
            $chapter = get_chapter($vo['id'], $id);
            file_put_contents($dir . '/_' . $chapter . '_' . $vo['sign'] . '.md', $vo['markdown'] . $foot);
        }
        // 下载目录压缩包
        $zipFile = $dir . '.zip';
        if (file_exists($zipFile)) {
            unlink($zipFile);
        }
        $zip = new \PharData($zipFile);
        $zip->buildFromDirectory($dir, '/\.md$/');
        if (!is_file($zipFile)) {
            $this->error('文档文件不存在');
        }
        if (ob_get_length() !== false) @ob_end_clean();
        header('Content-Type: application/zip');
        header('Content-Disposition:attachment;filename=doc_' . $book_name . '.zip');
        header('Content-Length:' . filesize($zipFile));
        @readfile($zipFile);
        @unlink($zipFile);
        exit();
    }

    // 添加
    public function add(array $req)
    {
        if (session('user.level') < 2) {
            $this->error('等级达到v2才能发布文集');
        }
        if ($this->isPost()) {
            $r = pdo()->trans(function () use ($req) {
                model('common.book')->save($req);
            });
            $this->_jump(['添加成功', '添加失败'], $r, 'user/index');
        }
        return view();
    }

    // 修改
    public function edit(int $id, array $req)
    {
        $model = model('common.book')->find($id);
        if (!$model) {
            $this->error('记录不存在');
        }
        // 验证权限
        if (!check_prem_level(3, $id)) {
            $this->error('非创建者无法进行此操作');
        }
        $vo = $model->toArray();
        if ($this->isPost()) {
            $r = pdo()->trans(function () use ($model, $req) {
                $model->save($req);
                widget_reload('doc'); // 清除doc缓存
            });
            $this->_jump(['修改成功', '修改失败'], $r, 'user/index');
        }
        return view()->with(['vo' => $vo]);
    }

    // 删除
    public function del(int $id)
    {
        if ($this->isAjax()) {
            $model = model('common.book')->find($id);
            if (!$model) {
                $this->error('记录不存在');
            }
            // 验证权限
            if (!check_prem_level(3, $id)) {
                $this->error('非创建者无法进行此操作');
            }
            $vo = $model->toArray();
            if ($vo['status'] != 0) {
                $this->error('请先停用后再删除');
            }
            $r = $model->del();
            $this->_jump(['删除成功', '删除失败'], $r, 'user/index');
        }
        $this->error('非法操作');
    }
}